/*
 * Copyright 2008 the original author Ang Gao.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * GoogleSearcher.java 2008-12-1
 */
package ie.ucc.cs.anggao.finalproject.server.searchengine;

import ie.ucc.cs.anggao.finalproject.client.model.SearchEngineResult;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @author GaoAng
 *
 */
public class GoogleSearcher extends BaseSearcher{

	private static final String googleKey = "ABQIAAAAyufcUCXVQptEag3uN91OCRTa_glYqoyxctY5svHxm9Gg_peXsRRYpuq5JUgyBqa6li-28JdzgMMonA";
	
	private Queue<String> querys;
	
	private int resultnumber;
	
	public int getResultnumber() {
		return resultnumber;
	}

	public GoogleSearcher(){
		super();
		querys = new LinkedList<String>();
	}
	
	public ArrayList<SearchEngineResult> getSEResults(){
		return this.results;
	}
	
	public void doIR(String q) {
		
		
		if(q.isEmpty()){
			return ;
		}
		querys.add(q);
		q = querys.poll();
		results.clear();
		URLConnection connection;

		String line;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader;

		JSONObject json;
		

		try {
			q = URLEncoder.encode(q, "UTF-8");
			URL url = new URL(
					"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&rsz=large&v=1.0&key="+googleKey+"&q="
							+ q);

			//Proxy
            InetSocketAddress addr = new InetSocketAddress("10.51.255.250",
                    8080);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); 
            
			connection = url.openConnection(proxy);

			// connection.addRequestProperty("Referer",
			// "http://www.mysite.com/index.html");

			reader = new BufferedReader(new InputStreamReader(connection
					.getInputStream()));

			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			json = new JSONObject(builder.toString());

//			System.out.println("Total results = " +json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount"));

			JSONArray ja = json.getJSONObject("responseData").getJSONArray("results");

			
			System.out.println("Google Produce Results: "+ja.length());
			this.resultnumber = ja.length();
			for (int i = 0; i < ja.length(); i++) {
//				System.out.print((i+1) + ". ");
				JSONObject j = ja.getJSONObject(i);
//				System.out.println(j.getString("titleNoFormatting"));
//				System.out.println(j.getString("url"));
					    
				SearchEngineResult result = new SearchEngineResult();
				result.setTitle(j.getString("titleNoFormatting"));
				result.setUrl(j.getString("url"));
				result.setDescription(j.getString("content"));
				
				results.add(result);
				
			}

			reader.close();
//			return results;
			
			
		} catch (Exception e) {
			
				e.printStackTrace();
		}
//		return null;
	}

}

